var userinfo;
function loadUserInfo(fn) {
    var t = cookie.Get('SSOTOKEN')
    if (t) {
        jQuery.get("/api/sso/myinfo?cb=cb", null, null);
    } else {

    }
}


function cb(info) {
    if (info.state == 1) {
        showLoginUi()
    } else {
        showUserInfo(info)
    }
}

// 登陆成功后，显示用户信息
function showUserInfo(msg) {

    var userinfo = msg.userinfo;
    $("#info .username").text(userinfo.username || userinfo.alias || userinfo.moblie );
    $("#info .wechat").text(userinfo.Wechat);
    $(".userinfo-nickname").text(userinfo.alias || userinfo.moblie);

}

// 登陆界面
function showLoginUi() {

    var htm = [];
    htm.push('<div class="loginwarp" >')
    htm.push('<a class="iconfont icon-help1 help"  title="登陆遇到问题！" href="/static/restore.html"></a>')
    htm.push('<h2 title="登陆"><em class="iconfont icon-denglu"></em> </h2>')
    htm.push('<form id="login">')
    htm.push('<span ><em class="iconfont icon-shouji"></em><input   type="text" placeholder="手机" name="username"  /></span>')
    htm.push('<span ><em class="iconfont icon-shoujiyanzhengma"></em><input   type="text" placeholder="密码" name="password"   /></span>')
    htm.push('<input type="hidden" name="redirecturl" />')
    htm.push('<a class="submit" >确定</a>')
    htm.push('</form>')
    htm.push('</div>')

    $('#dialog').html(htm.join('')).show();
    $('#dialog').find('.submit').click(commit)
    $('#dialog').find('.icon-close').click(closeDialog)
}

// 关闭dialog
function closeDialog() {
    $('#dialog').html('').hide();
}


// 登录提交
function commit(e) {
    var url = '/api/sso/login'
    var data = $("#login").serializeObject()

    var e = window.event || arguments.callee.caller.arguments[0]
    var el = e.srcElement || e.target
    $.post(url, data, loginResult.bind(this, el))

}

// 登录结果
function loginResult(el, msg) {
    switch (msg) {
        case 1:
            alert("提交方法不对!")
            el.style.display = 'block'
            break;
        case 2:
            el.style.display = 'block'
            alert("非法登录!")
            break;
        case 3:
            el.style.display = 'block'
            alert("手机号错误或不存在!")
            break;
        case 4:
            el.style.display = 'block'
            alert("密码错误!")
            break;
        default:
            el.style.display = 'none'
            closeDialog()
            if (cb) cb(msg)
            break;
    }
}
function logout() {
    $.get("/api/sso/logout", function (res) {
        res && res == 200, ( cookie.Del("SSOTOKEN"), location.href = "/")
    })
}

